﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Leo.Awesome.AppPlatform.Domain;
using Leo.Awesome.AppPlatform.Repostories;
using Volo.Abp.DependencyInjection;

namespace Leo.Awesome.AppPlatform.DomainServices
{

    public interface IMenuDataSeeder
    {
        Task SeedAsync(List<Menu> Menus, string domain = "default");

        Task<List<Menu>> GetAllListAsync(string domain = "default");

    }

    public class MenuDataSeeder : ITransientDependency, IMenuDataSeeder
    {
        private readonly IMenuRepository MenuRepository;

        public MenuDataSeeder(IMenuRepository MenuRepository)
        {
            this.MenuRepository = MenuRepository;
        }
        public virtual async Task SeedAsync(List<Menu> Menus, 
            string domain = "default")
        {
            if (Menus.IsNullOrEmpty())
            {
                return;
            }
            var codes = Menus.Select(x => x.Code).ToList();
            var entites = await MenuRepository.GetListAsync(x => codes.Contains(x.Code) 
            && x.Domain == domain);

            //if (entites.Any())
            //{
            //    return;
            //}
            Menus.ForEach(x =>
            {
                SetDomainRecursive(x, domain);
            });
            var existCodes = entites.Select(x => x.Code).ToList();
            foreach (var code in codes.Except(existCodes))
            {
                var Menu = Menus.FirstOrDefault(x => x.Code == code);
                if (Menu != null)
                {
                    await MenuRepository.InsertAsync(Menu);
                }
            }
        }

        private static void SetDomainRecursive(Menu Menu, string domain)
        {
            Menu.Domain = domain;

            foreach (var item in Menu.Items)
            {
                SetDomainRecursive(item, domain);
            }
        }

        public async Task<List<Menu>> GetAllListAsync(string domain = "default")
        {
            return await MenuRepository.GetListAsync(x => x.Domain == domain);
        }
    }

}
